/**
 * 
 */
package com.I9lou.se.lurker.search.support;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.MultiReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.I9lou.se.lurker.index.IndexWriterFactory;
import com.I9lou.se.lurker.search.IndexReaderFactory;

/**
 * NRT(Near real time) IndexReader实例工厂实现类。
 * 
 * 参考文档：http://wiki.apache.org/lucene-java/NearRealtimeSearch
 * 
 * @author chenwei
 * @date 2011-03-10
 * @ThreadSafe
 */
public class NRTIndexReaderFactory implements IndexReaderFactory {

	/**
	 * 日志输出
	 */
	private static Logger LOG = LoggerFactory.getLogger(NRTIndexReaderFactory.class);

	/**
	 * IndexWriter实例工厂
	 */
	private IndexWriterFactory indexWriterFactory = null;

	/**
	 * 设置IndexWriter实例工厂
	 * 
	 * @param indexWriterFactory
	 */
	public void setIndexWriterFactory(IndexWriterFactory indexWriterFactory) {
		this.indexWriterFactory = indexWriterFactory;
	}

	@Override
	public IndexReader create(String[] indexDirNames) {
		long startTime = System.currentTimeMillis();
		ArrayList<IndexReader> indexReaders = new ArrayList<IndexReader>();
		for (String indexDirName : indexDirNames) {
			IndexWriter writer = indexWriterFactory.get(indexDirName);
			if (writer != null) {
				try {
					long createStartTime = System.currentTimeMillis();
					indexReaders.add( IndexReader.open(writer, true) );
					LOG.info("***Add IndexReader[{}]. cost: {}ms", indexDirName,
							 System.currentTimeMillis() - createStartTime );
				} catch (IOException e) {
					LOG.error("***Create IndexReader[" + indexDirName
							  + "] failed!", e);
				}
			} else {
				LOG.error("***Create IndexReader[{}] failed: indexWriter can't be null!", indexDirName);
			}
		}
		if (indexReaders.size() == 0)
			throw new IllegalStateException("Create IndexReader failed! There is no index director for indexDirNames: "
							                + Arrays.toString(indexDirNames) + "!");
		IndexReader reader = null;
		if (indexReaders.size() == 1)
			reader = indexReaders.get(0);
		else
			reader = new MultiReader(indexReaders.toArray(new IndexReader[indexReaders.size()]));
		LOG.info("Create IndexReader success for indexDirNames: {}. cost: {}ms", 
				 Arrays.toString(indexDirNames),
				 System.currentTimeMillis() - startTime);
		return reader;
	}

}
